<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input id="username" type="text" placeholder="账号">
    <br>
    <input id="password" type="password" placeholder="密码">
    <br><br>
    <input type="button" value="模拟登录=>ajax(前端跳转:建议的做法)" onclick="login()">
    <br>
    <input type="button" value="模拟登录=>ajax(后端跳转:跳不动)" onclick="login2()">
    <br>
    <form action="../jump2" method="post">
        <input name="username" type="text" placeholder="账号">
        <br>
        <input name="password" type="password" placeholder="密码">
        <br><br>
        <input type="submit" value="模拟登录=>非ajax(后端跳转:会刷新页面)">
    </form>
    <script src="../util.js"></script>
    <script>
        var username = document.querySelector("#username");
        var password = document.querySelector("#password");
        function login(){
            //登录实际要发送ajax请求
            //实现方式一：前端发ajax，后端返回json，前端解析响应，判断是否要跳转
            ajax({
                method: "POST",
                url: "../jump",
                contentType: "application/x-www-form-urlencoded",
                body: "username="+username.value
                    +"&password="+password.value,
                callback: function(status, resp){
                    console.log("响应状态码："+status+", 响应正文："+resp)
                    //转换响应正文json字符串为json对象
                    var json = JSON.parse(resp);
                    if(json.ok){//登录成功
                        location.href = "response.html";
                    }else{//登录失败
                        alert("账号或密码错误");
                    }
                }
            })
        }
        function login2(){
            //实现方式二：前端发ajax，后端登录成功直接跳转，登录失败还是跳转本页面
            //存在问题：ajax不会刷新页面（不会跳转）
            ajax({
                method: "POST",
                url: "../jump2",
                contentType: "application/x-www-form-urlencoded",
                body: "username="+username.value
                    +"&password="+password.value,
                callback: function(status, resp){
                    console.log("响应状态码："+status+", 响应正文："+resp)
                    //转换响应正文json字符串为json对象
                    var json = JSON.parse(resp);
                    if(json.ok){//登录成功
                        location.href = "response.html";
                    }else{//登录失败
                        alert("账号或密码错误");
                    }
                }
            })
        }
    </script>
</body>
</html>